<template>
    <div id="order">
        <!--导航栏-->
        <van-nav-bar
                title="填写订单"
                left-arrow
                :fixed=true
                :border=true
                @click-left="onClickLeft"
        ></van-nav-bar>
        <!--收货地址-->
        <!-- 联系人卡片 -->
        <van-contact-card
            :type="address_type"
            add-text="选择收货地址"
            :name="address_name"
            :tel="address_phone"
            @click="chooseAddress"
            style="margin-top: 3rem"
    ></van-contact-card>

        <van-cell-group style="margin-top: 0.6rem">
            <van-cell title="送达时间" :value="arriveDate" is-link @click="showDatePopup">

            </van-cell>
            <router-link :to="{path:'/confirmOrder/OrderDetail'}">
                <van-cell :value="`共${goodsCount}件`" is-link :center=true>
                    <template slot="title">
                        <img :key="index" v-for="(goods,index) in threeShopCart" :src="goods.small_image" alt="" style="width: 3rem">
                    </template>
                </van-cell>
            </router-link>
        </van-cell-group>

        <van-cell-group style="margin-top: 0.6rem">
            <van-cell title="支付方式" value="微信" ></van-cell>
        </van-cell-group>

        <van-cell-group style="margin-top: 0.6rem">
            <van-cell title="备注" >
                <input slot="right-icon" type="text" placeholder="选填，请备注您的需求" v-model="notice">
            </van-cell>
        </van-cell-group>

        <van-cell-group style="margin-top: 0.6rem">
            <van-cell title="商品金额" :value="`￥${totalPrice}`" ></van-cell>
        </van-cell-group>

        <van-cell-group style="margin-top: 0.6rem">
            <van-cell title="配送费" :value="`￥${disParice}`" ></van-cell>
        </van-cell-group>

        <van-submit-bar
                :price="totalPrice*100+disParice*100"
                button-text="提交订单"
                label="实付"
                @submit="onSubmit"
        ></van-submit-bar>

        <!--弹出日期-->
        <van-popup v-model="dateShow" round position="bottom">
            <van-datetime-picker
                    v-model="currentDate"
                    type="datetime"
                    :min-date="minDate"
                    :max-date="maxDate"
                    @cancel="onDateCancel"
                    @confirm="onDateConfirm"
            ></van-datetime-picker>
        </van-popup>
        <!--支付二维码-->
        <van-popup v-model="isPay"round position="center">
            <qriously :value="qrcode" :size="200" />
        </van-popup>
        <transition name="router-slier" mode="out-in">
            <router-view></router-view>
        </transition>
    </div>
</template>

<script>
    import PubSub from 'pubsub-js'
    import Moment from 'moment'
    import {mapState} from 'vuex'
    import {Toast} from 'vant'
    import { postOrder,orderPaySuccess,getWXCode,queryPayStatus,getAllSelectedGoods,delAllSelectedGoods } from './../../service/api/index'
    export default {
        name: "Order",
        data(){
            return {
                //1.地址
                address_type:'add', // 地址卡片类型
                address_name:null,
                address_phone:null,
                address_id:null,

                //2.日期
                dateShow:false,
                minDate: new Date(2020, 0, 1),
                maxDate: new Date(2025, 10, 1),
                currentDate: new Date(),

                //3.送达时间
                arriveDate:"请选择送达时间",

                //4.备注
                notice:null,

                isPay:false, //是否显示二维码
                qrcode:null  //生成二维码的url地址
            }
        },
        computed:{
            ...mapState(['shopCart','userInfo']),
            //商品总件数
            goodsCount(){
                let selectedGoodsCount = 0
                Object.values(this.shopCart).forEach((goods,index)=>{
                    if(goods.checked){
                        selectedGoodsCount += 1
                    }
                })
                return selectedGoodsCount
            },
            //商品总价
            totalPrice(){
                let totalPrice = 0;
                Object.values(this.shopCart).forEach((goods,index)=>{
                    if(goods.checked){
                        totalPrice += goods.price * goods.num
                    }
                })
                return totalPrice
            },
            //取购物车前三件选中的
            threeShopCart(){
                let shopCart = [];
                Object.values(this.shopCart).forEach((goods,index)=>{
                    if(goods.checked) {
                        shopCart.push(goods)
                    }
                });
                return shopCart.slice(0,3)
            },
            //配送费
            disParice(){
                //商品大于40 免配送
                if(this.totalPrice > 40) {
                    return 0
                } else {
                    return 6
                }
            }
        },
        methods:{
            onClickLeft(){
                // alert('返回')
                this.$router.back()
            },
            chooseAddress(){
                this.$router.push({name:'myAddress'})
            },
            //提交订单
            async onSubmit(){
                //3.1 数据验证
                if(!this.address_id) {
                    Toast({
                        message:'请选择收货地址',
                        duration:500
                    })
                    return
                }

                if(this.arriveDate === '请选择送达时间') {
                    Toast({
                        message:'请选择送达时间',
                        duration:500
                    })
                    return
                }

                if(!this.notice) {
                    Toast({
                        message:'请添加注意事项',
                        duration:500
                    })
                    return
                }

                //3.2 处理订单相关
                if(this.userInfo) {
                    //3.2.1 查询购物车订单
                    let goodsResult =await getAllSelectedGoods(this.userInfo.token)
                    //3.2.2创建订单
                    if(goodsResult.success_code === 200){
                        let orderResult =await postOrder(this.userInfo.token, this.address_id, this.arrive_time,
                            goodsResult.data, this.notice, this.totalPrice, this.disParice);
                        //3.3.3 删除购物车中已经生成的商品
                        if( orderResult.success_code === 200 ) {
                            let delResult = await delAllSelectedGoods(this.userInfo.token)
                            //3.3.4 发起微信支付
                            if(delResult.success_code === 200) {
                                //测试用 1 分钱 ！！！！！！！！！！！！！！！！！！！！！！！！！！！
                                let urlResult = await getWXCode(orderResult.data.order_id,1)//测试用1分钱orderResult.data.total_price
                                if(urlResult.code_url) {
                                    this.isPay = true
                                    this.qrcode = urlResult.code_url
                                    //3.3.5 验证用户是否支付成功
                                    let payResult = await queryPayStatus(orderResult.data.order_id)
                                    if(payResult.success) {
                                        Toast({
                                            message:payResult.massage,
                                            duration:500
                                        })
                                        this.isPay = false
                                        //3.3.6 通知自己的服务器
                                        let statusResult = await orderPaySuccess(this.userInfo.token,orderResult.data.order_id)
                                        if(statusResult.success_code === 200) {
                                            //3.3.7 跳转路由
                                            this.$router.replace('/dashboard/mine')
                                            window.sessionStorage.setItem('tabBarActiveIndex','3')
                                        }
                                    }
                                }
                            } else {
                                Toast({
                                    message:'订单处理出错',
                                    duration:500
                                })
                            }
                        }
                    } else {
                        Toast({
                            message:'获取订单商品失败',
                            duration:500
                        })
                    }
                }
            },
            showDatePopup(){
                this.dateShow = true
            },
            //取消日期组件
            onDateCancel(){
                this.dateShow = false
            },
            //确认日期组件
            onDateConfirm(value){
                this.dateShow = false
                this.arriveDate = Moment(value).format('YYYY-M-D hh:mm:ss')
                console.log(this.arriveDate)
                console.log(value)
            },


        },
        mounted(){
            //接收收货地址
            PubSub.subscribe('userAddress',(msg,address)=>{
                if(msg === 'userAddress') {
                    //修改卡片类型
                    this.address_type = 'edit'
                    this.address_name = address.name
                    this.address_phone = address.tel
                    this.address_id = address.address_id
                }
            })
        },
        beforeDestroy(){
            PubSub.unsubscribe('userAddress')
        }
    }
</script>

<style scoped>
    #order{
        width: 100%;
        height: 100%;
        background-color: #F5F5F5;
    }

    .router-slier-enter-active, .router-slier-leave-active{
        transition: all 0.3s;
    }

    .router-slier-enter, .router-slier-leave{
        transform: translate3d(2rem,0,0);
        opacity: 0;
    }
</style>